package com.hax.security.filter;

import com.hax.constants.SecurityConstants;
import com.hax.security.CustomUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户每次请求的过滤器，校验token合法性等
 * 1. 校验token合法性
 * 2. token续期
 */
public class CustomRequestUsernamePasswordFilter extends OncePerRequestFilter {

    Logger logger = LoggerFactory.getLogger(CustomRequestUsernamePasswordFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        if (request.getRequestURI().contains(SecurityConstants.LOGIN_URL)) {
            //白名单放行，如果是/auth/login则证明是登录的接口，不需要校验token
            filterChain.doFilter(request, response);
            return;
        }
        String tokenHeader = request.getHeader("Authorization");
        if (!StringUtils.hasText(tokenHeader)) {
            // 返回token
            //正常这里要返回封装的result类
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("认证失败");
            return;
        }
        String token = tokenHeader.replace("Bearer ", "");
        logger.info("token is {}", token);
        // 校验token合法性
        //... 省略逻辑 这里从redis中拿出
        // token续期
        //... 省略逻辑 这里每次访问都将redis中的token续期
        // 将redis中存放的用户信息，放入SecurityContextHolder中
        UserDetails userDetails = new CustomUser("henry", "", null);
        // 放入SecurityContextHolder中，这一步很重要，否则spring security无法认证成功，会被AuthorizationFilter拦截器拦住
        SecurityContextHolder.getContext()
                .setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, null));
        filterChain.doFilter(request, response);
    }
}
